﻿package pl.krasi.facebook 
{
	import com.facebook.commands.feed.PublishUserAction;
	import com.facebook.data.events.FacebookEventData;
	import com.facebook.data.friends.GetFriendsData;
	import com.facebook.net.FacebookCall;
	import com.facebook.session.WebSession;
	import com.facebook.utils.FacebookConnectUtil;
	import com.facebook.utils.FacebookSessionUtil;
	import com.facebook.events.FacebookEvent;
	import com.facebook.commands.friends.*;
	import com.facebook.commands.users.*;
	import com.facebook.*;
	import com.facebook.data.users.*;
	import com.facebook.Facebook;
	import flash.events.Event;
	
	import com.facebook.utils.FacebookSessionUtil;
	import com.facebook.commands.notifications.*;
	import com.facebook.commands.stream.*;
	import flash.text.TextField;
	
	import flash.display.LoaderInfo;
	import flash.events.EventDispatcher;
	import com.facebook.*;
	import flash.net.URLLoader;

	
	/**
	 * ...
	 * @author Mblaszczyk
	 */
	public class Model extends EventDispatcher
	{
		private var _apiKey:String;
		private var _secret:String;
		
		public var _name:String = "";
		protected var fbSessionUtil:FacebookSessionUtil;
		protected var facebook:Facebook;
		protected var loader:URLLoader; 
		
		public var pictureData:Array;
		
		public function Model(loaderInfo:LoaderInfo) 
		{
			
			//setup API key & secret - no need in this metod. No go from IDE, only from www.
			
			fbSessionUtil = new FacebookSessionUtil ( loaderInfo.parameters.fb_sig_api_key , null , loaderInfo);
			facebook = fbSessionUtil.facebook;
			
			fbSessionUtil.addEventListener(FacebookEvent.CONNECT, onConnect);
			
			if ( loaderInfo.parameters.fb_sig_api_key )
			{
				trace ( "Parameters found, verifying ...") ;
				fbSessionUtil.activeSession.verifySession();
			} else {
				trace ( "No Parameters Found, Error! " ) ;
			}
		}
		
		private function getUsersUID():void {
			var call:FacebookCall = new GetFriends();
			call.addEventListener(FacebookEvent.COMPLETE, onGetUID, false, 0, true);
			facebook.post(call);
		}
		
		private function onGetUID(e:FacebookEvent) : void {
			trace ("wywolano event on Complete dla GetFriends ");
			//create array containing friends UID's
			var friends_uid : Array = new Array();
			
			//Get UID's from facebook's response
			var friends : Array = (e.data as GetFriendsData).friends.toArray();
			for each(var friend : FacebookUser in friends) friends_uid.push(friend.uid);
			
			friends_uid.unshift( facebook.uid);
			
			var call:FacebookCall = new GetInfo(friends_uid, new Array('name', 'pic_square'));
			//see field list ->  http://facebook-actionscript-api.googlecode.com/svn/release/current/docs/index.html
			call.addEventListener(FacebookEvent.COMPLETE, onGetUserData, false, 0, true);
			facebook.post(call);
		}
		
		private function onGetUserData(e:FacebookEvent) : void {
			trace("dane pobrano succ");
			var dane:Array =  (e.data as GetInfoData).userCollection.toArray();
			trace ("lista:", dane.length);
			
			pictureData = new Array();
			//Get the name of current logged user:
			_name = dane[0]['name'];
			_name = _name.substring(0, _name.indexOf(" "));
			
			for (var i:int = 1; i < dane.length; i++) {
				//trace (i, dane[i]['name'], dane[i]['pic_square']);
				if (dane[i]['pic_square'] != "") {
					pictureData.push(dane[i]);
				}
			}
			dispatchEvent(new Event(Event.COMPLETE));
		}
		
		/**
		 * This function is invoked after checking connection session.
		 * @param	e
		 */
		private function onConnect(e:FacebookEvent) : void {
			if ( e.error == null ) {
				trace ( " Facebook Connection: Verified" );
				getUsersUID();
			} else {
			trace ( " Facebook Connection: " + e.error.errorMsg );
			}
		}
		
		public function publishStory(_score:Number) : void {
			trace (_name + " scores: " + _score);
			//fbcall = new PublishPost("has played Friends of Snake", { 'href':'http://apps.facebook.com/friendsofsnake/', 'name':'Friends of Snake', 'caption':'', 'media':[ ] }, [ { 'href':'http://apps.facebook.com/flash_demo/', 'text':'Visit Facebook Flash Demo' } ], uid.toString());
			var infos:Array = new Array();
			infos['href'] = "http://apps.facebook.com/friendsofsnake/";
			infos['name'] = "Friends of Snake";
			infos['caption'] = _name + " got score of " + _score + ".\nCould you do better?";
			infos['media'] =  [ { 'type': 'image', 'src':  'http://www.gamemummy.com/facebook/flash_demo/api.jpg', 'href': 'http://apps.facebook.com/friendsofsnake/' } ];
			
			
			var links:Array = new Array();
			links = [ { 'href':'http://apps.facebook.com/friendsofsnake/', 'text':'Play Friends of Snake' } ];
			var call:FacebookCall = new PublishPost("has played Friends of Snake", infos, links);
			facebook.post(call);
		}
		
		private function getSomeData() : void {
		}
		
		private function onGetFriendsUID(e:FacebookEvent) : void {
		}
		
	}
	
}